<template>
  <div class="app-container" >
    <!--main search body-->
    <div>
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="素材id">
            <el-input
              v-model="queryParams.mediaId"
              placeholder="请输入素材id"
              clearable
              size="small"
            />
          </el-form-item>
        </el-form>
        <!--main search button -->
        <div class="search-button">
            <el-button type="primary" icon="el-icon-search" size="mini" :loading="bannerLoding" @click="getList">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" :loading="bannerLoding" @click="resetSearch">重置</el-button>
        </div>

      </div>

      <div class="add-options">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="showAddReplyView"  v-hasPermi="['system:user:add']">新增</el-button>
      </div>
      <!-- main list body -->
      <el-table v-loading="bannerLoding" :data="mediaList" :row-style="{'height':'90px'}" :stripe="true">
          <el-table-column label="素材id" align="center" prop="mediaId"  width="220" :show-overflow-tooltip="true"/>
          <el-table-column label="素材url" align="center" prop="mediaUrl"  width="220" :show-overflow-tooltip="true"/>
          <el-table-column label="素材类型" align="center" prop="mediaType"  width="160" :show-overflow-tooltip="true"/>
          <el-table-column label="素材描述" align="center" prop="description"  width="220" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" :show-overflow-tooltip="true"/>

          <!-- <el-table-column
            label="操作"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-dropdown @command="e=>handleCommand(e,scope)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="!scope.row.skuState && scope.row.skuJdState" command="up">上架</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.skuState && scope.row.skuJdState" command="down">下架</el-dropdown-item>
                  <el-dropdown-item v-if="!scope.row.skuState  ||  !scope.row.skuJdState" command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column> -->
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.rows"
          @pagination="getList"
      />
      <el-dialog  title="新增回复消息" :visible.sync="showAddMediaDailog" width="900px" append-to-body>
         
        <div>
          <el-form :model="addMediaParams" ref="addMediaForm" :rules="rules" :inline="false" label-width="110px" v-loading="mediaFormLoading">
            
            <el-form-item label="素材类型">
              <el-select v-model="addMediaParams.mediaType" class="media-type-selector" placeholder="请选择" @change="onMediaTypeChanged">
                <el-option v-for="item in replyTypes" :key="item.code" :label="item.name" :value="item.code" />
              </el-select>     
            </el-form-item>

            <el-form-item label="作者" prop="author"  v-if="addMediaParams.mediaType == 'news'">
              <el-input class="keyword-input" maxlength="10" show-word-limit placeholder="请输入作者" v-model="addMediaParams.author" />
            </el-form-item>

            <el-form-item label="标题" prop="title" v-if="addMediaParams.mediaType == 'video' || addMediaParams.mediaType == 'news' ">
              <el-input class="keyword-input" maxlength="30" show-word-limit placeholder="请输入标题" v-model="addMediaParams.title"/>
            </el-form-item>

            <el-form-item label="描述" prop="description" v-if="addMediaParams.mediaType != 'newsImg'" >
              <el-input class="keyword-input" type="textarea" maxlength="50" show-word-limit placeholder="请输入描述" v-model="addMediaParams.description"/>
            </el-form-item>

            <el-form-item label="内容" prop="content" v-if="addMediaParams.mediaType == 'news'">
              <el-input class="keyword-input" type="textarea" maxlength="600" show-word-limit placeholder="请输入内容" v-model="addMediaParams.content"/>
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">图文消息的具体内容，支持HTML标签，必须<br/>少于2万字符，小于1M，且此处会去除JS,涉<br/>及图片url必须来源 "上传图文消息内的图片获<br/>取URL" 接口获取。外部图片url将被过滤。</div>
                <i class="el-icon-warning-outline"></i>
              </el-tooltip>
            </el-form-item>

            <el-form-item label="摘要" prop="digest" v-if="addMediaParams.mediaType == 'news'">
              <el-input class="keyword-input" type="textarea" maxlength="50" show-word-limit placeholder="请输入摘要" v-model="addMediaParams.digest"/>
            </el-form-item>

            <el-form-item label="原文地址" prop="contentSourceUrl" v-if="addMediaParams.mediaType == 'news'">
              <el-input class="keyword-input" placeholder="请输入原文地址" v-model="addMediaParams.contentSourceUrl"/>
              <el-tooltip class="item" effect="dark" content="图文消息的原文地址，即点击“阅读原文”后的URL" placement="top-start">
                <i class="el-icon-warning-outline"></i>
              </el-tooltip>
            </el-form-item>

            <el-form-item label="封面图片id" prop="thumbMediaId" v-if="addMediaParams.mediaType == 'news'">
              <el-input class="keyword-input" placeholder="请输入封面图片id" v-model="addMediaParams.thumbMediaId"/>
              <el-tooltip class="item" effect="dark" content="图文消息的封面图片素材id（必须是永久mediaID)" placement="top-start">
                <i class="el-icon-warning-outline"></i>
              </el-tooltip>
              
            </el-form-item>

            <el-form-item label="是否显示封面" prop="showCoverPic" v-if="addMediaParams.mediaType == 'news'">
              <el-radio v-model="addMediaParams.showCoverPic" :label="1">是</el-radio>
              <el-radio v-model="addMediaParams.showCoverPic" :label="0">否</el-radio>
            </el-form-item>

            <el-form-item label="上传文件" prop="multipartFile" v-if="addMediaParams.mediaType != 'news'">
              <el-upload
                ref="upload"
                action=""
                :on-preview="handlePreview"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :file-list="this.fileList"
                :http-request="startUpload"
                :auto-upload="false"
                :show-file-list="true"
                :limit="1"
                >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">{{this.fileLimit[addMediaParams.mediaType]}}</div>
              </el-upload>
            </el-form-item>

            <el-form-item label="图片链接" v-if="addMediaParams.newsImgUrl != ''">
              <div :style="{'color':'rgba(80,220,80,1)'}">{{addMediaParams.newsImgUrl}}</div>
              <div :style="{'color':'red'}">请自行保存该URL, 界面一旦关闭则无法找回!!!</div>
            </el-form-item>

          </el-form>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="mediaFormLoading"  @click="confirmAddMedia('addMediaForm')">确 定</el-button>
        <el-button @click='cancelAddReply'>取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>

import {
    getMediaList,
    addMedia,
    uploadNewsContentImage
} from "@/api/mall/mediaApi";

export default {
  name: "MediaManage",
  components: {

  },
  data() {
    return {
      mediaList:[],
      total:0,
      bannerLoding:false,
      mediaFormLoading: false,
      queryParams:{
        mediaId: "",
        mediaType: "",
        description: "",
        startTime: "",
        endTime: "",
        page: 1,
        rows: 10
      },
      showAddMediaDailog:false, //添加弹出框
      replyTypes:[
        {name:"图片",code:"image"},
        {name:"视频",code:"video"},
        {name:"图文",code:"news"},
        {name:"图文内容图片",code:"newsImg"}
      ],
      fileLimit: {
        image: "支持bmp/png/jpeg/jpg/gif格式，且不超过10MB",
        video: "支持MP4格式，且不超过10MB",
        newsImg: "支持jpg/png格式，且不超过1MB"
      },
      // 新增回复参数
      addMediaParams: {},
      rules: {
          meidaType: [{ required: true, message: '请选择素材类型', trigger: 'change' }],
          author: [{ required: true, message: '请输入作者', trigger: 'change' }],
          title: [{ required: true, message: '请输入标题', trigger: 'change' }],
          description: [{ required: true, message: '请输入描述', trigger: 'change' }],
          content: [{ required: true, message: '请输入回复内容', trigger: 'change' }],
          digest: [{ required: true, message: '请输入摘要', trigger: 'change' }],
          thumbMediaId: [{ required: true, message: '请输入封面id', trigger: 'blur' }],
          contentSourceUrl: [{ required: true, message: '请输入原文地址', trigger: 'change' }],
          multipartFile: [{required: true, message: '请选择文件', trigger: 'change' }]
      },

      fileList:[],
      
    };
  },

  created() {
    this.getList();
  },

  methods: {

   initAddMediaParams() {
     let type = this.addMediaParams.mediaType || "image";
     this.addMediaParams = {
        mediaType: type,
        author: "",
        title: "",
        description: "",
        content: "",
        digest: "",
        thumbMediaId: "", // 图文素材封面id
        contentSourceUrl: "", // 图文素材原文地址
        showCoverPic: 1, // 是否显示封面
        multipartFile: null, // 素材文件
        suffix: "", //文件名后缀
        newsImgUrl: ""
      }
   },
  
    // 点击新增,显示添加回复消息界面
    showAddReplyView(){
      // 初始化参数字段
      this.$refs.addMediaForm && this.$refs.addMediaForm.resetFields();
      this.initAddMediaParams();
      this.showAddMediaDailog = true;
      
    },

    // 获取回复消息列表
    getList() {
      this.bannerLoding = true;
      getMediaList(this.queryParams).then(response => {
          this.bannerLoding = false;
          if(response.code==200){
            console.log("素材列表结果 ---->", response);
            this.mediaList = response.data.mediaList;
            this.total = response.data.total;
          } else {
            this.$message("数据获取失败");
          }
        }
      );
    },

    resetSearch() {
      this.queryParams.mediaId = "";
      this.getList();
    },

    handleChange(file, fileList) {
        console.log("选择的文件-->\n",file)
        this.addMediaParams.multipartFile = file;
        this.addMediaParams.suffix = file.name.substring(file.name.lastIndexOf('.'));
        // 手动校验表单数据
        this.$refs.addMediaForm.validateField("multipartFile");
    },

    handleRemove(file, fileList) {
        console.log("删除的文件-->\n",file)
        this.addMediaParams.multipartFile = null;
        this.addMediaParams.suffix = "";
        // 初始化图文内容的图片URL
        this.addMediaParams.newsImgUrl = "";
        // 手动校验表单数据
        this.$refs.addMediaForm.validateField("multipartFile");
    },

    handlePreview(file) {
      console.log(file);
    },

    startUpload(fileInfo) {
        this.addMediaParams.multipartFile = fileInfo.file;
        if (this.addMediaParams.mediaType == "newsImg") {
          // 如果newsImgUrl有值,则不再重复上传
          if ("" != this.addMediaParams.newsImgUrl) return this.mediaFormLoading = false;
          this.uploadNewsContentImage();
        } else {
          this.submitMedia();
        }
        
    },

    // 确认添加素材
    confirmAddMedia(formName) {
        this.mediaFormLoading = true;
        this.$refs[formName].validate((valid) => {
        if (valid) {
            if (this.addMediaParams.multipartFile) {
                this.$refs.upload.submit();
            } else {
                this.submitMedia();
            }
            
        } else {
          this.mediaFormLoading = false;
          console.log('error submit!!');
          return false;
        }
      });
    },

    submitMedia() {
        var formData = new FormData();
        formData.append("mediaType", this.addMediaParams.mediaType);
        formData.append("description", this.addMediaParams.description);

        if (this.addMediaParams.mediaType == "image") {
            formData.append("suffix", this.addMediaParams.suffix);
            formData.append("multipartFile", this.addMediaParams.multipartFile);

        } else if (this.addMediaParams.mediaType == "video") {
            formData.append("title", this.addMediaParams.title);
            formData.append("suffix", this.addMediaParams.suffix);
            formData.append("multipartFile", this.addMediaParams.multipartFile);

        } else if (this.addMediaParams.mediaType == "news") {
            formData.append("title", this.addMediaParams.title);
            formData.append("author", this.addMediaParams.author);
            formData.append("content", this.addMediaParams.content);
            formData.append("digest", this.addMediaParams.digest);
            formData.append("contentSourceUrl", this.addMediaParams.contentSourceUrl);
            formData.append("thumbMediaId", this.addMediaParams.thumbMediaId);
            formData.append("showCoverPic", this.addMediaParams.showCoverPic);

        }
        console.log("素材上传参数 -->",formData);

        addMedia(formData).then(res => {
          console.log("素材上传结果---->",res);
          if(200 === res.code) {
            this.$alert('素材添加完成', '提示', {
              confirmButtonText: '确定',
              showClose: false,
              callback: action => {
                // 如果当前在第一页, 自动刷新复数据
                if (this.queryParams.page === 1) {
                  this.getList()
                }
              }
            });
            this.showAddMediaDailog = false;
          }
          this.mediaFormLoading = false;
            
        })
    },

    // 上传图文素材内容图片
    uploadNewsContentImage() {
      var formData = new FormData();
      formData.append("mediaType", this.addMediaParams.mediaType);
      formData.append("suffix", this.addMediaParams.suffix);
      formData.append("multipartFile", this.addMediaParams.multipartFile);

      uploadNewsContentImage(formData).then(res => {
        console.log("图文消息里的图片上传结果 --->", res);
        if (200 === res.code) {
          this.addMediaParams.newsImgUrl = res.data.url;
        } else {
          alert("文件上传出现异常, 请稍后再试")
        }
        this.mediaFormLoading = false;
      })
    },

    // 取消添加回复消息
    cancelAddReply() {
      this.showAddMediaDailog = false;
    },

    // 选择回复消息类型
    onMediaTypeChanged(value) {
        console.log('初始化媒体文件信息和表单校验信息');
        this.initAddMediaParams();
        this.$refs.upload && this.$refs.upload.clearFiles();
        this.$refs.addMediaForm.clearValidate();
    }

  }
};
</script>

<style scoped>
  .search-button{
    display:flex;
    justify-content: center;
    margin-bottom: 10px;
  }
  .add-options{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  /* .el-input input{border:none;} */
  .media-type-selector{
    width: 160px
  }

  .keyword-input {
    width: 400px;
    margin-right: 5px;
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
</style>
